<?php
//UMA new
namespace App\Console\Commands;

use App\Services\NikkeiService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Models\Nikkei as nikkeiModel;

class nikkei extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'nikkei:insert';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'save nikkei data into database';

    /**
     *
     */
    private $nikkeiService;

    /**
     * Create a new command instance.
     *
     * @param NikkeiService $nikkeiService
     */
    public function __construct(NikkeiService $nikkeiService)
    {
        parent::__construct();
        $this->nikkeiService = $nikkeiService;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {


        //查看数据库中属否有昨天的日经数据
        //昨日の日経データがデータベースにあるか確認してください
        $nikkeiNotExist = $this->nikkeiService->getNikkeiDatabaseData();
        if ($nikkeiNotExist) {
            try {
                $date = now()->subDay()->toDateString();
                $content = $this->nikkeiService->getNikkeiData($date);
                \Log::info($content);
                if ($content) {
                    nikkeiModel::create($content);
                }
            } catch (\Exception $e) {
                Log::info('Add Failed', ['msg' => $e->getMessage(), 'time' => date('Y-m-d H:i:s', time())]);
                $this->error('failed to get nikkei data');
                return null;
            }
        }
        $this->info('nikkei datas created successfully'.PHP_EOL);

    }
}
